<?php
/**
*	商户产品类 
*   +----------------------------------------------------------------------
*   | Author: ONLY <491518132@qq.com>
*	+----------------------------------------------------------------------
*   | Creater Time : 2013-5-27
*   +----------------------------------------------------------------------
*   | Link ( http://www.goshopx.com  http://www.shopingj.com )
*   +----------------------------------------------------------------------
**/

	class UserProduct {
		protected $producto2o,$uid,$description,$product,$priceo2o,$priceb2b,$tags;
		function __construct( $model='Layout' ){
			$this->product = M('Product');
			$this->producto2o = M('Product_o2o');
			$this->description = M('ProductDescription');
			$this->descriptiono2o = M('ProductDesO2o');
			$this->priceo2o = M('ProductPriceO2o');
			$this->priceb2b = M('ProductPriceB2b');
		}
		
		/**
		 * 返回商户产品列表信息
		 * @param string $_keyword
		 * @return array $prolistinfo
		 */
		function busprolist($_proids){
			$prolistinfo = array();
			foreach ($_proids as $k => $v){
				$prolistinfo[$k]['id'] = $v;
				$prolistinfo[$k]['price'] = $this->_price($v);
				$prolistinfo[$k]['image'] = $this->_mainimage($v);
				$temp = $this->_description($v);
				$prolistinfo[$k]['name'] = $temp['name'];
				$prolistinfo[$k]['alias'] = $temp['alias'];
				
			}
			return $prolistinfo;
		}
		
		/**
		 * 商户产品IDS
		 * @param string $_uid
		 * @param array $_keyword
		 * @return array $proids
		 */
		function uidtoproids($_uid,$_keyword = false){
			$proids = array();
			$where['user_id'] = $_uid;
			$where['status'] = '1';
			$proids = $this->producto2o->field('product_id')->where($where)->select();
			$proids = $this->_arr2to1($proids,'product_id');
			if($_keyword){
				$kproids = $this->_keyword($_keyword);
				$proids = array_intersect($proids, $kproids);
			}
			return $proids;
		}
		
		/**
		 * 返回产品基本信息
		 * @param int $_uid
		 * @param array $_limit
		 * @param int $_status
		 * @return array $proinfo
		 */
		function prolistinfo ($_uid,$_limit = 20,$_status) {
			$where['user_id'] = $_uid;
			$where['status'] = $_status ? $_status : array('NEQ',3);
			$proinfo = $this->producto2o->field('id,user_id,product_id,status')->where($where)->limit($_limit)->select();
			foreach ($proinfo as $k => &$v){
				$temp = $this->_description($v['product_id']);
				$v['name'] = $temp['name'];
				$v['price'] = $this->price($v['product_id'], $_uid);
			}
			return $proinfo;
		}
		
		/**
		 * 
		 * @param unknown $_uid
		 * @param unknown $_tagid
		 * @param unknown $_status
		 * @param number $_limit
		 * @return Ambigous <multitype:, number, unknown, mixed, boolean, multitype:multitype: >
		 */
		function tagtoproinfo($_uid,$_tagid,$_status,$_limit = FALSE){
			$model = M();
			$field = 'o.product_id as id,o.user_id as uid,p.image,d.name as name,do.name as o_name,do.addition_info';
			$status =  $_status ? $_status : 1;
			$_limit = $_limit ? "LIMIT ".$_limit : '';
			$where = "o.user_id=$_uid AND t.tags_id=$_tagid AND p.status=1 AND o.status=$status";
			$sql = "select $field from tags_obj as t LEFT JOIN product_o2o as o ON t.obj_id=o.product_id LEFT JOIN product as p ON p.id=t.obj_id LEFT JOIN product_description as d ON d.product_id=t.obj_id LEFT JOIN product_des_o2o as `do` ON do.product_id=t.obj_id WHERE $where GROUP BY id ORDER BY t.sequence,t.id DESC $_limit";
			$proids = $model->query($sql);
// 			echo $model->getLastSql();
// 			exit;
			foreach ($proids as $k => $v){
				$proids[$k]['price'] = $this->price($v['id'], $v['uid']);
				if($proids[$k]['o_name']){
					$proids[$k]['name'] = $proids[$k]['o_name'];
				}
			}
			return $proids;
		}
		
			/**
		 * 返回产品基本、各个价格、状态信息
		 * @param int|array  $_proids
		 * @param unknown_type $_uid
		 * @param unknown_type $_uid
		 * @return array $info
		 */
		function propricestatus($_proids,$_tagid,$_uid,$_sequence = 'DESC',$_status = 1) {
			$model=D('PStatusPriceInfo');
			$where=array();
			$where['product_id']=is_array($_proids) ? array('IN',implode(',', $_proids)) : $_proids;
			if($_status) $where['pstatus']  = $_status;
			$where['user_id']=$_uid;
			$where['_string'] = "ta.tags_id=".$_tagid;
			$info = $model->where($where)->order("ta.sequence,ta.id DESC")->select();
//  		echo $model->getLastSql();
// 			dump($info);
// 			exit;
			return $info;
		}
		
		/**
		 * 检查商户产品表（ product_o2o）该用户下有没有该产品
		 * @param int|string $_uid
		 * @param int|string $_proid
		 * @return array $reid
		 */
		function checkpro($_uid,$_proid){
			$model = M('ProductO2o');
			$where = array();
			$where['user_id'] = $_uid;
			$where['product_id'] = $_proid;
			$res = $model->field('id,status')->where($where)->find();
			return $res;
		}
		
		/**
		 * 检查商户产品缓存表中( product_des_o2o)，该用户下有没有该产品
		 * @param int|string $_uid
		 * @param int|string $_proid
		 * @return array $reid
		 */
		function checkprodes($_uid,$_proid){
			$model = M('ProductDesO2o');
			$where = array();
			$where['user_id'] = $_uid;
			$where['product_id'] = $_proid;
			$res = $model->field('id,status')->where($where)->find();
			return $res;
		}
		
		/**
		 * 返回此产品详细信息
		 * @param string $_proid
		 * @param array $_uids
		 * @return array $oneproinfo
		 */
		function oneproinfo($_proid,$_uids = false){
			$cateid = $this->_procate($_proid);
			$name = $this->_description($_proid);
			$image = $this->_mainimage($_proid);
			$oneproinfo = array();
			if(is_array($_uids)){
				foreach ($_uids as $k => $v){				
					$oneproinfo[$k]['id'] = $_proid;
					$oneproinfo[$k]['uid'] = $v;
					$oneproinfo[$k]['name'] = $name['name'];
					$oneproinfo[$k]['alias'] = $name['alias'];
					$oneproinfo[$k]['cateid'] = $cateid[0]['category_tag_id'];
					$oneproinfo[$k]['image'] = $image;
					$oneproinfo[$k]['binfo'] = $this->businessinfo($v);
					$oneproinfo[$k]['price'] = $this->price($_proid,$v);
					if($oneproinfo[$k]['price'] <= 0){
						unset($oneproinfo[$k]);
					}
				}
			}elseif($_uids){
				$oneproinfo['uid'] = $_uids;
				$oneproinfo['des'] = $name;
				$oneproinfo['image'] = $image;
				$oneproinfo[$k]['cateid'] = $cateid[0]['category_tag_id'];
				$oneproinfo['code'] = $this->_procode($_proid);
				$oneproinfo['groupimage'] = $this->_image($_proid);
				$oneproinfo['imagecount'] = count($oneproinfo['groupimage']);
				$oneproinfo['price'] = $this->price($_proid,$_uids);
				$oneproinfo['binfo'] = $this->businessinfo($_uids);
			}else{
				$this->_message($_uids, __LINE__, '用户错误');
			}
			return $oneproinfo;
		}

		/**
		 * 返回产品分类
		 * @param int | array | string $_ids
		 * @return array $cateid
		 */
		function _procate($_ids){
			$model = M('ProductToCategoryTag');
			$where['product_id'] = is_array($_ids) ? count($_ids) > 1 ? array('IN',implode(',', $_ids)) : array_shift($_ids) : $_ids;
			$cateid = $model->field('category_tag_id')->where($where)->select();
			// 		echo $model->getLastSql();
			return $cateid;
		}
	
		/**
		 * 返回有此产品的商户IDS
		 * @param sting $_proid
		 * @return array $uids
		 */
		function protouid($_proid){
			$where['status'] = '1';
			$where['product_id'] = $_proid;
			$uids = $this->producto2o->field('user_id')->where($where)->select();
			$uids = $this->_arr2to1($uids,'user_id');
			return $uids;
		}
		
		/**
		 * 返回商户全部产品IDS
		 */
		function busallpro($_uid = false){
			$model = M();
			$sql = "SELECT o.product_id as id FROM product_o2o as o LEFT JOIN product_price_o2o as pro ON o.product_id=pro.product_id AND o.user_id=pro.user_id LEFT JOIN product p ON p.id=o.product_id WHERE o.`status`=1 AND o.user_id=".$_uid;
			$proids = $model->query($sql);
// 			echo $model->getLastSql();
// 			dump($proids);
// 			exit;
			$proids = $this->_arr2to1($proids);
			return $proids;
		}
		
		/**
		 * 
		 * @return Ambigous <multitype:array, multitype:string, multitype:, string, multitype:unknown >
		 */
		function o2oallpro(){
			$model = M();
			$where = array();
			$where['status'] = 1;
			$proids = $this->producto2o->field('product_id as id')->where($where)->group('product_id')->select();
			$proids = $this->_arr2to1($proids);
// 			echo $model->getLastSql();
// 			dump($proids);
			return $proids;
		}
		
		/**
		 * 随机返回商家产品
		 * @param string $_limit
		 * @param array $map
		 * @return $proids
		 */
		function randpro ($_limit,$levle=0,$map=array()) {
			$where['product_id'] = array('ELT',10000);
			$where['status'] = 1;
			$where = array_merge($where,$map);
			$proids = $this->producto2o->field('product_id,user_id')->where($where)->order('rand()')->limit($_limit)->select();
			if($proids){
				$ids=arr_to_explode($proids,'product_id',',');
				$reid = $this->product->field('id')->where(array('id'=>array('IN',$ids),'status'=>1))->select();
				$ids=arr_to_explode($reid,'id',',');
				$ids=explode(',', $ids);
				$newarr=array();
				foreach ($proids as $v){
					if(in_array($v['product_id'],$ids)){
						$newarr[]=$v;
					}
				}
				$prolist = array();
				$prolist = $this->_prolistinfo($newarr);
				foreach ($prolist as $k => $v){
					if($v['price'] < 2 ){
						unset($prolist[$k]);
					}
				}
				if(count($prolist) < 5&&$levle<3){
					$levle++;
					$prolist=$this->randpro($_limit,$levle);
				}
			}
			return $prolist;
		}
		
		/**
		 * 根据IDS返回商品信息
		 * @param array $_proids
		 * @param string $_uid
		 * @return array $proinfo
		 */
		function proinfo($_proids,$_uid) {
			$model = M();
			$field = "o.product_id as id,o.user_id as uid,p.image,p.name as name,deo.name as o_name,deo.addition_info";
// 			$field = "o.product_id as id,o.user_id as uid,p.image,d.name as name,deo.name as o_name,deo.addition_info";
			$where = "o.product_id IN (".implode(',',$_proids).") AND o.user_id=".$_uid." AND deo.user_id=".$_uid;
			$sql = "SELECT $field FROM product_o2o as o LEFT JOIN product as p ON o.product_id=p.id LEFT JOIN product_des_o2o as deo ON deo.product_id=o.product_id WHERE $where";
// 			$sql = "SELECT $field FROM product_o2o as o LEFT JOIN product as p ON o.product_id=p.id LEFT JOIN product_description as d ON d.product_id=o.product_id LEFT JOIN product_des_o2o as deo ON deo.product_id=o.product_id WHERE $where";
			$proinfo = $model->query($sql);
			if($_REQUEST['mw']){
				echo $model->getLastSql();
			}
			return $proinfo;
		}
		
		/**
		 * 返回产品列表信息
		 * @param array $_proids
		 * @return array $proinfo;
		 */
		function _prolistinfo ($_proiduid){
			$proinfo = array();
			$name = $this->_description($_proiduid);
			$images=$this->_mainimage($_proiduid);
			foreach ($_proiduid as $k => $v){
				$proinfo[$v['product_id']]['name'] = $name[$v['product_id']]['name'];
				$proinfo[$v['product_id']]['alias'] = $name[$v['product_id']]['alias'];
				$proinfo[$v['product_id']]['image'] = $images[$v['product_id']]['image'];
				$proinfo[$v['product_id']]['cid'] = $v['user_id'];
				$proinfo[$v['product_id']]['price'] = $this->price($v['product_id'],$v['user_id']);
			}
			return $proinfo;
		}
		
		/**
		 * 商户后台商品列表
		 * @param unknown_type $_uid
		 * @return Ambigous <unknown, string>
		 */
		function businessinfo($_uid){
			$site = M();
			$sql = "SELECT * FROM site as s LEFT JOIN site_description as d ON s.id=d.site_id WHERE s.user_id=$_uid";
			$businfo = $site->query($sql);
			$businfo = $businfo['0'];
			if ( $businfo ) $businfo['address'] = $this->_address($_uid);
			return $businfo;
		}
		
		/**
		 * 返回店名
		 * @param string $_uid
		 * @return string $name
		 */
		function _shopname($_uid){
			$site = M('Site');
			$name = $site->field('name')->where(array('user_id'=>$_uid))->find();
			return $name['name'];
		}
		
		/**
		 * 返回用户地址
		 * @param unknown_type $_uid
		 * @return string
		 */
		function _address($_uid,$_type = TRUE){
			$add = M('O2oStore');
			$addr = $add->field('province,city,district,address')->where(array('pid'=>$_uid))->find();
// 			echo $add->getLastSql();
			$address='';
			if($_type){
				if($addr['province']){
					$address = $this->aera($addr['province']).$this->aera($addr['city']).$this->aera($addr['district']).$addr['address'];
				}
				return $address;
			}else{
				return $addr;
			}
		}
		
		/**
		 * 商户搜索
		 * @param string $_proname
		 * @param string $_uid
		 * @param string $_shopname
		 * @return array $pros || $uid
		 */
		function search($_proname = false,$_shopname = false,$_uid = false ,$status = 1){
			if($_uid && $_proname){
				$_uid ? $whereo['user_id'] = $_uid : false;
				$where['name'] = array('like','%'.$_proname.'%');
				$whereo['status'] = $status;
				$whereo['user_id'] = $_uid;
				$pros = $this->description->field('product_id')->where($where)->select();
				$pros = $this->_arr2to1($pros,'product_id');
				$uproid = $this->producto2o->field('product_id')->where($whereo)->group('product_id')->select();
				if($_REQUEST['mw']){
					echo $this->producto2o->getLastSql();
// 					dump($uproid);
				}
				$uproid = $this->_arr2to1($uproid,'product_id');
				$proids = array_intersect($pros, $uproid);
				if($_REQUEST['mw']){
					dump($proids);
				}
				return $proids;
			}else{
				if($_proname){
					$where['name'] = array('like','%'.$_proname.'%');
					$proids = $this->description->field('product_id')->where($where)->select();
					$usproid =  $this->busallpro();
					$proids = $this->_arr2to1($proids,'product_id');
					$proids = array_intersect($proids, $usproid);
					return $proids;
				}elseif($_shopname){
					$where['name'] = array('like','%'.$_shopname.'%');
					$site = M('Site');
					$uid = $site->field('user_id')->where($where)->select();
					$uid = $this->_arr2to1($uid,'user_id');
					return $uid;
				}
			}
		}
		
		/**
		 * 
		 * @param unknown_type $_id
		 * @return Ambigous <>
		 */
		function aera($_id){
			$aera = M('Area');
			$address = $aera->field('name')->find($_id);
			return $address['name'];
		}
		
		
		/**
		 * 关键字搜索
		 * @param string $_keyword
		 * @return array $proids 产品IDS
		 */
		function _keyword($_keyword){
			$proids = $this->productlist();
			$proids = explode(',', $proids);
			$where['product_id'] = array('IN',$proids);
			$where['name'] = array('like','%'.$_keyword.'%');
			$proids = $this->description->field('product_id')->where($where)->select();
			$proids = $this->_arr2to1($proids,'product_id');
			return $proids;
		}
		
		
		/**
		 * 获取单个产品价格
		 * @param string $_proid 产品ID
		 * @param string $_uid 用户ID
		 * @param bloom $_uid 输出价格 默认为元
		 * @return array $price
		 */
		function price($_proid, $_uid ,$_unit = TRUE){
			// 获取缓存信息
			$cache = $this->get_product_cache($_uid, $_proid);
			if($cache){
				if($cache[$_proid]['sale']){
					return round($cache[$_proid]['sale']*0.01);			
				}
			}
			
			$model = M();
// 			$where = 'o.user_id='.$_uid.' AND o.product_id='.$_proid.' AND o.start_time<'.NOW_TIME.' AND o.end_time>'.NOW_TIME.' AND (o.price>0 OR o.add>0 OR o.percent>0)';
			$where = 'o.user_id='.$_uid.' AND o.product_id='.$_proid.' AND (o.price>0 OR o.`add`>0 OR o.percent>0)';
			$field = 'b.jiayi,o.product_id,o.price,o.`add`,o.percent,o.start_time,o.end_time';
// 			$temp = $model->query( " SELECT $field FROM product_price_o2o AS o LEFT JOIN product_price_b2b AS b ON b.product_id=o.product_id WHERE $where ORDER BY o.start_time DESC LIMIT 1" );
			$temp = $model->query( " SELECT $field FROM product_price_o2o AS o LEFT JOIN product_price_b2b AS b ON b.product_id=o.product_id WHERE $where" );
// 			echo $model->getLastSql();
			$temp = $temp['0'];
			$priceb = $temp['jiayi']; //基价
			$pricep = $temp['price']; //自定义价格
			$pricea = $temp['add']; //增加的价
			$pricepe = $temp['percent']; //百分比价
			$price = 0;
			if($pricep > 0){
				$price = $pricep;
			}elseif($pricea > 0){
				$price = $pricea + $priceb;
			}elseif($pricepe > 0){
				$price = round($priceb * (1 + $pricepe*0.01));
			}
			if($_unit){
				$price = round($price*0.01);
			}
			return $price;
		}
		
		/**
		 * 设置商品的上下架状态  //$pro_ids...商品ID   $sta...商品上下架状态
		 * @param int $key
		 * @return boolean true/false
		 */
		public function setprosta($user_id ,$pro_ids, $sta = 0){
		    $map['user_id'] = $user_id;
			$map['product_id'] = array('in',$pro_ids);
			$res = $this->producto2o->where($map)->setField('status',$sta);
			if(empty($res)){ return false; }
			return true;
		}
		
		
		/**
		 * 返回单个产品的最高、低价
		 * @param string $_proid
		 * @return array $minmax
		 */
		function minmax($_proid){
			$baseprice = $this->priceb2b->field('jiayi')->where(array('product_id'=>$_proid))->find();
			$where['product_id'] = $_proid;
			$maxp = $this->_price_o2o('MAX(`price`) as p', $where);
			$maxa = $this->_price_o2o('MAX(`add`) as a', $where);
			$maxpe = $this->_price_o2o('MAX(`percent`) as pe', $where);
			$max = $min = 0;
			$maxp = $maxp['p'];
			$maxa = ($maxa['a'] + $baseprice['jiayi']);
			$maxpe = round($baseprice['jiayi'] * (1 + $maxpe['pe']/100));
			$max = max(array($maxp,$maxa,$maxpe));
			//$max = $maxp > $maxa  ? $maxp : $maxa;
			//$max = $max > $maxpe ? $max : $maxpe;
			$where['price'] = array('GT',0);
			$minp = $this->_price_o2o('MIN(`price`) as p', $where);
			$compare[] = $minp['p'];
			unset($where['price']);
			$where['add'] = array('GT',0);
			$mina = $this->_price_o2o('MIN(`add`) as a', $where);
			$compare[] = $mina['a'] > 0 ? $mina['a'] + $baseprice['jiayi'] : 100000000000000;
			
			unset($where['add']);
			$where['percent'] =  array('GT',0);
			$minpe = $this->_price_o2o('MIN(`percent`) as pe', $where);
			$compare[] = $minpe['pe'] ? round($baseprice['jiayi'] * (1 + $minpe['pe']/100)) : 100000000000000;
			
			//去掉为空的值
			foreach ($compare as $key=>$v){
				if($v==''){
					unset($compare[$key]);
				}
			}
			$min =  min($compare);
			
			$minmax = array();
			$minmax['max'] = round($max/100);
			$minmax['min'] = round($min/100);
			return $minmax;
		}
		
		/**
		 * 商品信息统计
		 *
		 */
		function product_count($user_id){
			$m = 'product_o2o';
			$map['user_id'] = $user_id;
			$procount['total'] = $this->count($m,$map); //商品总数
			$map['status'] = 1;
			$procount['sj'] = $this->count($m,$map); //上架商品
			$map['status'] = 2;
			$procount['xj'] = $this->count($m,$map); //下架商品
				
			$m = "tags";
			$map = array();
			$map['user_id'] = $user_id;
			$map['type'] = 1;
			$procount['protags'] = $this->count($m, $map);
			$map['type'] = 2;
			$procount['articletags'] = $this->count($m, $map);
				
			return $procount;
		}
		
		
		/**
		 * 统计方法
		 *
		 */
		function count($m,$map){
			$model = M($m);
			$count = $model->where($map)->count();
			return $count;
		}
		
		
		function _price_o2o ($_field,$_where) {
			$price = $this->priceo2o->field($_field)->where($_where)->find();
			return $price;
		}
		
		
		/**
		 * 产品描述
		 * @param int or array $_proid
		 * @return array $des
		 */
		function _description($_pid,$field='product_id'){
			if(is_array($_pid)){
				$pids=arr_to_explode($_pid,$field,',');
				$description = $this->description->field('id,init_id,key_id',true)->where(array('product_id'=>array('IN',$pids)))->select();
				if($description){
					$description=field2key($description,'product_id');
				}
			}else{
				$description = $this->description->field('id,init_id,key_id',true)->where(array('product_id'=>$_pid))->find();
			}
			return $description;
		}
		
	
		/**
		 * 获取产品图片
		 * @param mixed $id 产品ID
		 * @return array
		 */
		function _image($_id,$field='product_id'){
			$dao = M("ProductImage");
			$where=array();
			if(is_array($_id)){
				$pids=arr_to_explode($_id,$field,',');
				$where['product_id']=array('IN',$pids);
				$description = $this->description->field('url')->where()->select();
				if($description){
					$description=field2key($description,'product_id',2);
				}
			}else{
				$where['product_id'] = $_id;
				$gorugimage = $dao->field('url')->where($where)->select();
			}
			return $gorugimage;
		}
		
		/**
		 * 返回产品的编码号
		 * @param string $_proid
		 * @return string $code
		 */
		function _procode($_proid){
			$code = $this->product->field('code')->where(array('id'=>$_proid))->find();
			return $code['code'];
		}

		/**
		 * 返回此产品属于那个用户ID
		 * @param string $_proid
		 * @return string $userid
		 */
		function _protouser($_proid){
			$where['product_id'] = $_proid;
			$userid = $this->producto2o->field('user_id')->where($where)->find();
			return $userid['user_id'];
		}
		
		/**
		 * 返回产品主图
		 * @param string $_proid
		 * @return array $mainimage
		 */
		function _mainimage($_proid,$field='product_id'){
			$image = M('Product');
			$cateid = $this->_procate($_proid);
			if(is_array($_proid)){
				$_proid=arr_to_explode($_proid,$field,',');
				$mainimage = $image->field('id,image')->where(array('id'=>array('IN',$_proid)))->select();
				$mainimage=field2key($mainimage,'id');
			}else{
				$mainimage = $image->field('image')->where(array('id'=>$_proid))->find();
				$mainimage=$mainimage['image'];
				if ( $cateid[0]['category_tag_id'] == 186 ) $mainimage = '/Public/v2/img/lhbg.jpg';
			}
			return $mainimage;
		}
		/**
		 * 二维数组返回一维或字符串
		 * @param array $_arr
		 * @param string $_field
		 * @param string $_type 1为数组 2为字符串
		 * @return multitype:array|multitype:string
		 */
		function _arr2to1($_arr,$_field = 'id',$_type = '1'){
			if ( ! $_arr ) return array();
			$arrayids = array();
			foreach ($_arr as $k => $v){
				$arrayids[$k] = $v[$_field];
			}
			if($_type != '1') $arrayids = implode(',',$arrayids);
		
			return $arrayids;
		}
		
		
		/**
		 * 返回提示信息
		 * @param multitype $_val
		 * @param json
		 */
		function _message($_val,$_line,$_msg){
			if(!$_val || empty($_val) || $_val === 'false'){
				$mesg=array("status"=>0,'msg'=>$_msg.'在'.$_line.'行');
				exit(json_encode($mesg));
			}else{
				$mesg=array("status"=>1,'msg'=>$_msg);
				exit(json_encode($mesg));
			}
		}
		
		/**
		 * 返回二维数组里面元素的交集
		 * @param array $_arr 二维数组
		 * @return $value 返回二维数组里面元素的交集
		 */
		function intersection($_arr) {
			$value = array();
			$init = true;
			if(count($_arr) == '1'){
				return array_shift($_arr);
			}else{
				foreach ($_arr as $k => $v){
					if(empty($value) && $init){
						$value = $v;
					}else{
						$value = array_intersect($value,$v);
						$init = false;
					}
				}
				return $value;
			}
		}
		
		/**
		 * 添加、修改
		 * @param array $_data 数据
		 * @param string $_model 模型
		 * @param string $_type 动作名
		 */
		function add_updata ($_data,$_model = 'Layout',$_type = 'add') {
			$model = M("$_model");
			if($_data){
				$reid = $model->create($_data);
				if($reid){
					if($_type == 'add'){
						$reid = $model->add();
						if($this->Debug) dump($model->getLastSql());
						return $reid;
					}elseif($_type == 'updata'){
						$reid = $model->save();
						if($this->Debug) dump($model->getLastSql());
						return $reid;
					}else{
						$this->_message(false, '请传入正确的动作！', __LINE__);
					}
				}else{
					$this->_message(false, "创建模型失败！", __LINE__);
				}
			}else{
				$this->_message(false, '没有数据！', __LINE__ );
			}
		}
		
		/**
		 * 删除数据
		 * @param array $_id
		 * @param model $_model
		 * @return string $reid
		 */
		function delete($_id,$_model){
			$model = M($_model);
			if($_id){
				$where['id'] = is_array($_id) ? array('IN',implode(',', $_id)) : $_id;
				$reid = $model->where($where)->delete();
				if($this->Debug) dump($model->getLastSql());
				return $reid;
			}else {
				$this->_message($_id, __LINE__, '请传入ID！');
			}
		}
		
		/**
		 * 获取产品列表
		 * @param int $_uid
		 * @param int or array $_proid （注：多个产品id，用数组）
		 * @param $descrition 是否查找详细信息。 false：不返回，ture：返回
		 * @return array $list
		 */
		function product_info($_uid , $_proid , $descrition = FALSE , $field='*'){
			//查找缓存表
			$cache = $this->get_product_cache($_uid, $_proid ,$field);
			
			//如果存在，获取相关信息
			$pid_array = is_array($_proid) ? $_proid : array($_proid);
			$list = array();
			foreach ($pid_array as $pid){
				if($cache[$pid] && !$update){
					//dump('test : 产品'.$pid . '有缓存，用缓存表');
					$cache[$pid]['jiayi'] = round($cache[$pid]['jiayi']/100);
					$cache[$pid]['sale'] = round($cache[$pid]['sale']/100);

					$list[$pid] = $cache[$pid];
				}else{
 					//dump('test : 产品'.$pid . '无缓存，查找基本信息表');
					$data = $this->pro_bascinfo($_uid, $pid);

					//更新缓存表
					$this->set_product_cache($_uid, $pid,$data);
					
					//拼装数组
					$data['jiayi'] = round($data['jiayi']/100);
					$data['sale'] = round($data['sale']/100);
					$list[$pid] = $data;
				}
				//返回产品详细信息
				if($descrition){
					$list[$pid]['des'] = $this->_description($pid);
					$list[$pid]['groupimage'] = $this->_image($pid);
					$list[$pid]['binfo'] = $this->businessinfo($_uid);
				}
			}
			return $list;
		}
		
		/**
		 * 用户浏览记录
		 * @param 用户ID $_uid
		 * @param 返回条数 $_limit
		 * @return array $Info
		 */
		function o2oseelog($_uid,$_limit = '0,10'){
			$model = M('Clicks');
			$where = array();
			$where['user_id'] = $_uid;
			$where['plantform'] = 'biz';
			$proids = $model->field('productid,user_id,cid')->where($where)->order('id DESC')->group('productid')->limit($_limit)->select();
// 			echo $model->getLastSql();
// 			dump($proids);
			$info = array();
			foreach ($proids as $k => $v){
				$temp = $this->proinfo(array($v['productid']), $v['cid']);
				$info[$k] = array_shift($temp);
				$price = $this->price($v['productid'], $v['cid']);
				if($price < 1){
					unset($info[$k]);
				}else{
					$info[$k]['price'] = $price;
				}
			}
// 			dump($info);
// 			exit;
			return $info;
		}
		
		/**
		 * 获取基本信息
		 * @param int $_uid 商户id
		 * @param int $pid 产品id
		 * @return array $data
		 */
		function pro_bascinfo($_uid ,$pid){
			$map=array();
			$map['product_o2o.user_id'] = $_uid;
			$map['product_o2o.product_id'] = $pid;
			$res = $this->producto2o
			->join(' product as p on product_o2o.product_id = p.id')
			->join(' product_description as pd on product_o2o.product_id = pd.product_id')
			->join(' product_price_b2b as ppb on product_o2o.product_id = ppb.product_id')
			->join(' product_price_o2o as ppo on product_o2o.product_id = ppo.product_id and product_o2o.user_id = ppo.user_id')
			->field('product_o2o.product_id,product_o2o.user_id,product_o2o.status,p.code,p.image,pd.name,ppb.jiayi,ppo.price,ppo.add,ppo.percent')
			->where($map)->find();
				
			$data['product_id'] = $pid;
			$data['user_id'] = $_uid;
			$data['jiayi'] = $res['jiayi'];
			//计算价格
			$sale = 0;
			if($res['price'] > 0){
				$sale = $res['price'];
			}elseif($res['add'] > 0){
				$sale = intval($res['jiayi']) + intval($res['add']);
			}elseif($res['percent'] > 0){
				$sale = round(intval($res['jiayi']) * (1 + intval($res['percent'])*0.01));
			}
			$data['sale'] = $sale;
			$data['name'] = $res['name'];
			$data['code'] = $res['code'];
			$data['image'] = $res['image'];
			$data['status'] = $res['status'];
				
			//获取产品分类
			$cate = $this->_procate($pid);
			$data['cate_id'] = $cate[0]['category_tag_id'];
			
			return $data;
		}
		
		
		/**
		 * 批量更新商户产品缓存
		 * @param int $_uid 用户id
		 * @param int or array $_proid 产品id		 
		 * @return int $reid
		 */
		function update_pro_cache($_uid,$_proid= ''){			
			$arr_pids = is_array($_proid) ? $_proid : array($_proid);
								
			foreach ($arr_pids as $pid){
				$data = $this->pro_bascinfo($_uid, $pid);							
				$reid = $this->set_product_cache($_uid, $pid , $data);
				
			}							
			return $reid;
		}
		
		/**
		 * 更新系统被迫下架的产品
		 * @param array $list 一个产品缓存数组
		 */
		function set_sys_prosta($list){
			foreach ($list as $vo){
				$data = array();
				$data['id'] = $vo['id'];
				//如果  B2B价格是否>1 ,并且商品是否被系统下架 ，则系统给商品上架
				$product = $this->product->field('id,price')->where('id='.$vo['product_id'])->find();
				if($vo['status']==0 && $product['price']>1){
					$status = 1;
				}elseif($product['price']<1){
					$status = 0;
				}
				
				$data['status'] = $status;
				//更新 O2O表中状态为下架
				$this->setprosta($vo['user_id'], $vo['product_id'] ,$status);
				//更新O2O缓存表状态为下架
				$this->set_product_cache($vo['user_id'] , $vo['product_id'] ,$data , 'update');
				
			}
					
		}
		
		/**
		 * 获取商户产品缓存lo-
		 * @param int $_uid 用户id
		 * @param int or array $_proid 产品id
		 * @param strint $field 产品字段
		 * @return array $cache 返回缓存数据
		 */
		function get_product_cache($_uid , $_proid , $field='*'){
			$map['user_id'] = $_uid;
			$map['product_id'] = is_array($_proid) ? array('in' , implode(',', $_proid)) : $_proid;
			
			$cache = $this->descriptiono2o->field($field)->where($map)->select();
			$cache=field2key($cache,'product_id');
			
			//更新系统被迫下架的产品
			if($cache){
				$this->set_sys_prosta($cache);
			}
			return $cache;
		}
		
		/**
		 * 设置商户产品缓存
		 * @param int $_uid 用户id
		 * @param int or array $_proid 产品id
		 * @param array $data 保存或者更新的数据
		 * @param string $handel add：保存，update：更新 , delete : 删除
		 * @return int $reid
		 */

		function set_product_cache($_uid , $_proid ,$data = array(),$handel = ''){
			$model = M('ProductDesO2o');	
			if(!$handel){
				$map['user_id'] = $_uid;
				$map['product_id'] = $_proid;
				$res = $model->where($map)->find();
				$data['id'] = $res['id'];
				$handel = empty($res) ? 'add' : 'update';				
			}	
			if($handel == 'add'){
				$reid = $model->add($data);
			}else if($handel == 'update'){
				$reid = $model->save($data);
			}
			return $reid;
		}
		
		
		//新表修改后的新函数
		
		/**
		 * 关键字搜索
		 * @param string $_keyword
		 * @param string $_uid
		 * @return array $proids
		 */
		function searchs($_keyword,$_uid){
			$model = M();
			$proids = array();
			$sql = "SELECT p.id FROM `product` p LEFT JOIN product_o2o o ON p.id=o.product_id LEFT JOIN tags_obj t ON o.product_id=t.obj_id WHERE p.`status`=1 AND o.`status`=1 AND o.user_id=".$_uid." AND p.`name` LIKE '%".$_keyword."%'";
			$hash = md5 ($sql);
			$exits = S ( $hash );
			if(empty($exits) && $hash != S($sql)){
				$proids = $model->query($sql);
				$proids = $this->_arr2to1($proids);
				$proids = array_unique($proids);
				// 				echo $model->getLastSql();
				S('proids',$proids,200);
				S('sql',$sql,200);
			}else{
				$proids = S($proids);
			}
			return $proids;
		}
		
	}